<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

// 登录表单默认值
const DEFAULT_EMAIL = 'ab@123.com'
const DEFAULT_PASSWORD = 'aaaaaa'

// 注册表单默认值
const DEFAULT_Register_Username = 'abc'
const DEFAULT_REGISTER_EMAIL = 'vg@123.com'
const DEFAULT_REGISTER_PHONE = '13800138000'
const DEFAULT_REGISTER_PASSWORD = 'aaaaaa'
const DEFAULT_REGISTER_CONFIRM_PASSWORD = 'aaaaaa'

// 定义组件状态
const isLogin = ref(true)
const loginError = ref(false)

// 登录表单
const loginForm = reactive({
  email: '',
  password: ''
})

// 注册表单
const registerForm = reactive({
  username: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: ''
})

// 切换表单模式
const toggleForm = () => {
  isLogin.value = !isLogin.value
  loginError.value = false
}

// 填充默认登录信息
const fillDefaultLogin = (field: 'email' | 'password'): void => {
  if (field === 'email' && !loginForm.email) {
    loginForm.email = DEFAULT_EMAIL
  } else if (field === 'password' && !loginForm.password) {
    loginForm.password = DEFAULT_PASSWORD
  }
}

// 填充默认注册信息
const fillDefaultRegister = (field: 'username' | 'email' | 'phone' | 'password' | 'confirmPassword'): void => {
  if (field === 'username' && !registerForm.username) {
    registerForm.username = DEFAULT_Register_Username
  } else if (field === 'email' && !registerForm.email) {
    registerForm.email = DEFAULT_REGISTER_EMAIL
  }else if (field === 'phone' && !registerForm.phone) {
    registerForm.phone = DEFAULT_REGISTER_PHONE
  }else if (field === 'password' && !registerForm.password) {
    registerForm.password = DEFAULT_REGISTER_PASSWORD
  }else if (field === 'confirmPassword' && !registerForm.confirmPassword) {
    registerForm.confirmPassword = DEFAULT_REGISTER_CONFIRM_PASSWORD
  }
}

const registerDefaultUser = () => {
  // 获取所有用户信息
  const users = JSON.parse(localStorage.getItem('users') || '{}')
  
  // 检查默认用户是否已存在
  if (!users[DEFAULT_EMAIL]) {
    // 注册默认用户
    users[DEFAULT_EMAIL] = {
      username: '默认用户',
      email: DEFAULT_EMAIL,
      phone: '13800138000',
      registerTime: new Date().toISOString()
    }
    
    localStorage.setItem('users', JSON.stringify(users))
    console.log('默认用户注册成功')
  }
}

const handleLogin = () => {
  loginError.value = false
  
  if (!loginForm.email || !loginForm.password) {
    alert('请填写所有字段')
    return
  }

  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(loginForm.email)) {
    alert('请输入有效的邮箱地址')
    return
  }

  // 获取所有用户信息
  const users = JSON.parse(localStorage.getItem('users') || '{}')
  
  // 检查用户是否存在
  if (users[loginForm.email]) {
    // 登录成功
    localStorage.setItem('currentUser', JSON.stringify({
      email: loginForm.email,
      username: users[loginForm.email].username,
      loginTime: new Date().toISOString()
    }))
    router.push('/post-login-choice')
    return
  }

  if (loginForm.email === DEFAULT_EMAIL && loginForm.password === DEFAULT_PASSWORD) {
    // 使用默认用户信息登录
    localStorage.setItem('currentUser', JSON.stringify({
      email: DEFAULT_EMAIL,
      username: '默认用户',
      loginTime: new Date().toISOString()
    }))
    router.push('/post-login-choice')
    return
  }
  
  // 登录失败处理
  loginError.value = true
  setTimeout(() => {
    router.push('/login-error')
  }, 500)
}

// 处理注册
const handleRegister = () => {
  if (!registerForm.username || !registerForm.email || !registerForm.phone || !registerForm.password || !registerForm.confirmPassword) {
    alert('请填写所有字段')
    return
  }

  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(registerForm.email)) {
    alert('请输入有效的邮箱地址')
    return
  }

  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(registerForm.phone)) {
    alert('请输入有效的手机号码')
    return
  }

  if (registerForm.password.length < 6) {
    alert('输入的密码长度至少为6位')
    return
  }

  if (registerForm.password !== registerForm.confirmPassword) {
    alert('两次输入的密码不一致')
    return
  }

  // 获取所有用户信息
  const users = JSON.parse(localStorage.getItem('users') || '{}')
  
  // 检查邮箱是否已被注册
  if (users[registerForm.email]) {
    alert('该邮箱已被注册')
    return
  }
  
  // 保存新用户信息
  users[registerForm.email] = {
    username: registerForm.username,
    email: registerForm.email,
    phone: registerForm.phone,
    registerTime: new Date().toISOString()
  }
  
  localStorage.setItem('users', JSON.stringify(users))
  
  alert('注册成功！')
  
  isLogin.value = true
}

onMounted(() => {
  registerDefaultUser()
  
  if (route.query.register === 'true') {
    isLogin.value = false
  }
})
</script>

<template>
<div class="auth-container">
    <div class="auth-card">
      <div class="auth-header">
        <h2 class="auth-title">{{ isLogin ? '用户登录' : '用户注册' }}</h2>
        <div class="auth-toggle">
          <button 
            @click="toggleForm" 
            class="toggle-btn"
            :class="{ active: isLogin }"
          >
            登录
          </button>
          <button 
            @click="toggleForm" 
            class="toggle-btn"
            :class="{ active: !isLogin }"
          >
            注册
          </button>
        </div>
      </div>
      
      <div class="auth-form-container">
        <!-- 登录表单 -->
        <form v-if="isLogin" @submit.prevent="handleLogin" class="auth-form">
          <div class="form-group">
            <label for="login-email">邮箱</label>
            <div class="input-wrapper">
              <i class="icon-email"></i>
              <input 
                id="login-email"
                type="email" 
                v-model="loginForm.email" 
                placeholder="请输入邮箱"
                @focus="fillDefaultLogin('email')"
                required
              />
            </div>
          </div>
          
          <div class="form-group">
            <label for="login-password">密码</label>
            <div class="input-wrapper">
              <i class="icon-password"></i>
              <input 
                id="login-password"
                type="password" 
                v-model="loginForm.password" 
                placeholder="请输入密码"
                @focus="fillDefaultLogin('password')"
                required
              />
            </div>
          </div>
          
          <!-- 登录错误提示 -->
          <div v-if="loginError" class="error-message">
            <i class="icon-error"></i>
            邮箱或密码错误，请重新输入
          </div>
          
          <button type="submit" class="submit-btn">登录</button>
        </form>
        
        <!-- 注册表单 -->
        <form v-else @submit.prevent="handleRegister" class="auth-form">
          <div class="form-group">
            <label for="register-username">用户名</label>
            <div class="input-wrapper">
              <i class="icon-user"></i>
              <input 
                id="register-username"
                type="text" 
                v-model="registerForm.username" 
                placeholder="请输入用户名"
                @focus="fillDefaultRegister('username')"
                required
              />
            </div>
          </div>
          
          <div class="form-group">
            <label for="register-email">邮箱</label>
            <div class="input-wrapper">
              <i class="icon-email"></i>
              <input 
                id="register-email"
                type="email" 
                v-model="registerForm.email" 
                placeholder="请输入邮箱"
                @focus="fillDefaultRegister('email')"
                required
              />
            </div>
          </div>
          
          <div class="form-group">
            <label for="register-phone">手机号</label>
            <div class="input-wrapper">
              <i class="icon-phone"></i>
              <input 
                id="register-phone"
                type="tel" 
                v-model="registerForm.phone" 
                placeholder="请输入手机号"
                @focus="fillDefaultRegister('phone')"
                required
              />
            </div>
          </div>
          
          <div class="form-group">
            <label for="register-password">密码</label>
            <div class="input-wrapper">
              <i class="icon-password"></i>
              <input 
                id="register-password"
                type="password" 
                v-model="registerForm.password" 
                placeholder="请输入密码（至少6位）"
                @focus="fillDefaultRegister('password')"
                required
              />
            </div>
          </div>
          
          <div class="form-group">
            <label for="register-confirm-password">确认密码</label>
            <div class="input-wrapper">
              <i class="icon-password"></i>
              <input 
                id="register-confirm-password"
                type="password" 
                v-model="registerForm.confirmPassword" 
                placeholder="请再次输入密码"
                @focus="fillDefaultRegister('confirmPassword')"
                required
              />
            </div>
          </div>
          
          <button type="submit" class="submit-btn">注册</button>
        </form>
      </div>
      
      <!-- 添加 Gitee 仓库地址 -->
      <div class="gitee-link">
        <p>Gitee 仓库地址: 
          <a href="https://gitee.com/xdyui/todolist__project" target="_blank">
            仓库
          </a>
        </p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.auth-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: rgb(0, 128, 96);
  padding: 20px;
}

.auth-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 450px;
  overflow: hidden;
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.auth-header {
  background: linear-gradient(135deg, #42b983 0%, #42b983 100%);
  padding: 30px;
  text-align: center;
  position: relative;
}

.auth-title {
  color: white;
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 20px 0;
}

.auth-toggle {
  display: flex;
  justify-content: center;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 30px;
  padding: 5px;
}

.toggle-btn {
  flex: 1;
  background: transparent;
  border: none;
  color: rgba(255, 255, 255, 0.7);
  padding: 10px 20px;
  border-radius: 30px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.toggle-btn.active {
  background: white;
  color: #42b983;
  font-weight: 600;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.auth-form-container {
  padding: 30px;
}

.auth-form {
  display: flex;
  flex-direction: column;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
  font-size: 15px;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-wrapper .icon-user,
.input-wrapper .icon-email,
.input-wrapper .icon-phone,
.input-wrapper .icon-password,
.input-wrapper .icon-error {
  position: absolute;
  left: 15px;
  color: #999;
  z-index: 1;
}

.input-wrapper .icon-user::before,
.input-wrapper .icon-email::before,
.input-wrapper .icon-phone::before,
.input-wrapper .icon-password::before,
.input-wrapper .icon-error::before {
  content: "";
  display: inline-block;
  width: 20px;
  height: 20px;
  background-size: contain;
  background-repeat: no-repeat;
}

.input-wrapper .icon-user::before {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23999'%3E%3Cpath d='M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z'/%3E%3C/svg%3E");
}

.input-wrapper .icon-email::before {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23999'%3E%3Cpath d='M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z'/%3E%3C/svg%3E");
}

.input-wrapper .icon-phone::before {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23999'%3E%3Cpath d='M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z'/%3E%3C/svg%3E");
}

.input-wrapper .icon-password::before {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23999'%3E%3Cpath d='M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z'/%3E%3C/svg%3E");
}

.input-wrapper .icon-error::before {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23f44336'%3E%3Cpath d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z'/%3E%3C/svg%3E");
}

.form-group input {
  width: 100%;
  padding: 15px 15px 15px 50px;
  border: 2px solid #e1e5e9;
  border-radius: 10px;
  font-size: 16px;
  box-sizing: border-box;
  transition: all 0.3s ease;
}

.form-group input:focus {
  outline: none;
  border-color: #42b983;
  box-shadow: 0 0 0 3px rgba(66, 185, 131, 0.2);
}

.submit-btn {
  background: linear-gradient(135deg, #42b983 0%, #359469 100%);
  color: white;
  border: none;
  border-radius: 10px;
  padding: 16px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-top: 10px;
  box-shadow: 0 4px 15px rgba(66, 185, 131, 0.3);
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(66, 185, 131, 0.4);
}

.submit-btn:active {
  transform: translateY(0);
}

.error-message {
  color: #f44336;
  background-color: #ffebee;
  padding: 15px;
  border-radius: 10px;
  margin-bottom: 15px;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.error-message .icon-error {
  margin-right: 10px;
}

/* 添加 Gitee 链接样式 */
.gitee-link {
  margin-top: 20px;
  text-align: center;
  font-size: 14px;
  color: #666;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.gitee-link a {
  color: #42b983;
  text-decoration: none;
  font-weight: 500;
}

.gitee-link a:hover {
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .auth-card {
    margin: 10px;
  }
  
  .auth-header {
    padding: 20px;
  }
  
  .auth-form-container {
    padding: 20px;
  }
  
  .auth-title {
    font-size: 24px;
  }
}
</style>